#include <iostream>

using std::cout;
using std::endl;

class Complex{
public:
    Complex(double dreal=0.0,double dimag=0.0)
    : _dreal(dreal)
    , _dimag(dimag)
    {
        cout<<"构造函数"<<endl;
    }

    Complex(const Complex &rhs)
    : _dreal(rhs._dreal)
    , _dimag(rhs._dimag)
    {
        cout<<"拷贝构造"<<endl;
    }

    ~Complex(){
        cout<<"析构函数"<<endl;

    }

    double getReal() const{ //注意看重载运算符函数那里，lhs和rhs是两个const版本的
        return _dreal;
    }

    double getImag() const{
        return _dimag;
    }

    void print() const{
        cout<<_dreal<<"+"<<_dimag<<"i"<<endl;
    }

private:
    double _dreal;
    double _dimag;
};

//如果使用Complex& operator+(const Complex &lhs, const Complex &rhs)返回
//返回临时对象的引用是不安全的，因为临时对象会在返回后销毁。
//可能会导致悬空引用（dangling reference）
Complex operator+(const Complex &lhs, const Complex &rhs){
    return Complex(lhs.getReal()+rhs.getReal(),lhs.getImag()+rhs.getImag());
}

/*
Complex operator+(const Complex &lhs, const Complex &rhs){
    Complex com(lhs.getReal()+rhs.getReal(),lhs.getImag()+rhs.getImag());
    return com;
}
*/

void test(){
    Complex c1(1,3);
    c1.print();

    Complex c2(2,6);
    c2.print();

    cout<<endl;
    Complex c3 = c1 + c2;
    c3.print();
}


int main()
{   
    test();
    return 0;
}

